package com.bk.bookviews.service.impl;

import com.bk.bookviews.common.Constants;
import com.bk.bookviews.common.Pagination;
import com.bk.bookviews.domain.UserInfo;
import com.bk.bookviews.domain.UserInfoExample;
import com.bk.bookviews.exception.BusinessException;
import com.bk.bookviews.exception.BusinessExceptionEnum;
import com.bk.bookviews.mapper.UserInfoMapper;
import com.bk.bookviews.service.UserInfoService;
import com.bk.bookviews.util.Md5Util;
import com.bk.bookviews.util.RedisUtil;
import com.bk.bookviews.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public UserInfo selectUserByPhone(String userPhone) {
        UserInfoExample example = new UserInfoExample();
        example.createCriteria().andUserPhoneEqualTo(userPhone);
        List<UserInfo> userInfos = userInfoMapper.selectByExample(example);
        return CollectionUtils.isEmpty(userInfos) ? null : userInfos.get(0) ;
    }

    @Override
    public void register(UserInfo userInfo) {
        UserInfo userInfo1 = selectUserByPhone(userInfo.getUserPhone());
        // 校验是否已注册
        if (userInfo1 != null){
            throw new BusinessException(BusinessExceptionEnum.USER_IS_EXIST);
        }

        // 密码加密
        String pwd = Md5Util.encryptMD5(userInfo.getUserPwd(), true);
        userInfo.setUserPwd(pwd);
        userInfoMapper.insert(userInfo);
    }

    @Override
    public UserInfo login(UserInfo userInfo) {
            UserInfo userInfo1 = selectUserByPhone(userInfo.getUserPhone());
            // 校验用户是否存在
            if (userInfo1 == null){
                throw new BusinessException(BusinessExceptionEnum.USER_IS_NULL);
            }
            // 失效前次登录token
            String tokenPix = Constants.PERFIX_TOKEN +userInfo1.getUserId();
            Set<String> patternKey = redisUtil.getPatternKey(tokenPix + '%');
            if (!CollectionUtils.isEmpty(patternKey)){
                for (Iterator iterator = patternKey.iterator(); iterator.hasNext();) {
                    String key = (String) iterator.next();
                    redisUtil.del(key);
                }
            }

            // 校验用户状态
            if (!Constants.NORAMAL.equals(userInfo1.getUserStatus())){
                throw new BusinessException(BusinessExceptionEnum.USER_STATUS_ERROR);
            }
            // 校验密码
            String pwd = Md5Util.encryptMD5(userInfo.getUserPwd(), true);
            if (!pwd.equals(userInfo1.getUserPwd())){
                throw new BusinessException(BusinessExceptionEnum.PWD_IS_ERROR);
            }
            // 存redis
            String token = UUIDUtils.getCode();
            redisUtil.set(tokenPix+token,userInfo1,Constants.EXPIRE_TIME);
            userInfo1.setUserPwd(null);
            userInfo1.setToken(tokenPix +token);
            System.out.println(userInfo1);
            return userInfo1;
    }

    @Override
    public UserInfo selectUser(Long userId) {
        return userInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public Pagination selectUserList(UserInfo userInfo) {
        UserInfoExample example = new UserInfoExample();
        UserInfoExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(userInfo.getUserPhone())){
            criteria.andUserPhoneLike("%"+userInfo.getUserPhone()+"%");
        }
        if (StringUtils.isNotBlank(userInfo.getUserStatus())){
            criteria.andUserStatusEqualTo(userInfo.getUserStatus());
        }
        criteria.andUserRoleEqualTo(Constants.SIMPLE_USER);
        return new Pagination(userInfoMapper.selectByExample(example));
    }

    public void updateUser(UserInfo userInfo) {
        UserInfo userInfo1 = selectUser(userInfo.getUserId());
        if (userInfo1 == null){
            throw new BusinessException(BusinessExceptionEnum.USER_NOT_EXIST);
        }
        if (StringUtils.isNotBlank(userInfo.getUserPwd())){
            // 密码加密
            String pwd = Md5Util.encryptMD5(userInfo.getUserPwd(), true);
            userInfo.setUserPwd(pwd);
        }
        if (StringUtils.isNotBlank(userInfo.getUserPhone()) && !userInfo.getUserPhone().equals(userInfo1.getUserPhone())){
            UserInfo userInfo2 = selectUserByPhone(userInfo.getUserPhone());
            if (userInfo2 != null){
                throw new BusinessException(BusinessExceptionEnum.PHONE_REPEAT);
            }
        }
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }
}
